package com.borball.store.comp;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableRowSorter;

import com.borball.store.dao.CardDAO;
import com.borball.store.dao.CompositeDAO;
import com.borball.store.dao.CustomerDAO;
import com.borball.store.dao.CustomerMoneyDAO;
import com.borball.store.dao.OrderDAO;
import com.borball.store.dao.OrderItemDAO;
import com.borball.store.dao.PStoreLogDAO;
import com.borball.store.dao.ProductStoreDAO;
import com.borball.store.domain.Card;
import com.borball.store.domain.Composite;
import com.borball.store.domain.Customer;
import com.borball.store.domain.CustomerMoney;
import com.borball.store.domain.OrderItem;
import com.borball.store.domain.PStoreLog;
import com.borball.store.domain.ProductAmount;
import com.borball.store.domain.ProductOrder;
import com.borball.store.domain.ProductStore;
import com.borball.store.domain.User;
import com.borball.store.util.StoreChangeActions;
import com.borball.store.util.UserUtils;

import craky.component.CommonTableModel;
import craky.componentc.JCButton;
import craky.componentc.JCComboBox;
import craky.componentc.JCLabel;
import craky.componentc.JCMessageBox;
import craky.componentc.JCNumberField;
import craky.componentc.JCPopupMenu;
import craky.componentc.JCScrollTable;
import craky.componentc.JCScrollText;
import craky.componentc.JCTable;
import craky.componentc.JCTableHeader;
import craky.componentc.JCTextField;
import craky.keeper.EmptyComponent;
import craky.keeper.KeeperApp;
import craky.keeper.KeeperPane;
import craky.layout.LineLayout;

public class PreSalePane extends KeeperPane {

	private static final long serialVersionUID = 4098577503066953853L;

	private static final String CMD_ADDMORE = "AddMore";
	
	private static final String[] COLUMNS_NAME = { "订单ID", "客户", "经手人", "操作员","时间", "产品", "数量", "单位", "单价", "总货款", "销售类型", "是否已付款" };

	protected KeeperApp keeper;

	protected User currentUser;

	protected CommonTableModel<OrderItem> model;

	protected List<OrderItem> data = new ArrayList<OrderItem>();

	protected OrderItem currentData;

	protected Action insertAction, deleteAction, addAction, cancelAction, completeAction;

	protected JCTable table;

	protected JCPopupMenu popup;

	protected JComponent top, bottom, center;

	protected JComponent ecUser, ecMemo, ecCustomer, ecTotals, ecProducts, ecAmount, ecPrice, ecPurpose, ecTotal, ecStatus, ecLogid;
	
	protected JCComboBox cpUser, cpCustomer, cpProducts, cpPurpose, cpStatus;
	
	protected JCNumberField cpAmount, cpTotal, cpTotals, cpPrice;
	protected JCTextField cpLogid;
	
	protected JCScrollText cpMemo;
	
	private JCButton btnDelete, btnInsert, btnAdd, btnCancel, btnComplete;

	private int selectedIndex;

	private OrderDAO orderDAO = new OrderDAO();
	private OrderItemDAO orderItemDAO = new OrderItemDAO();
	private CustomerDAO customerDAO = new CustomerDAO();
	private CardDAO cardDAO = new CardDAO();
	private CustomerMoneyDAO customerMoneyDAO = new CustomerMoneyDAO();
	private CompositeDAO compositeDAO = new CompositeDAO();
	private ProductStoreDAO productStoreDAO = new ProductStoreDAO();
	private PStoreLogDAO pStoreLogDAO = new PStoreLogDAO();
	
	public PreSalePane(KeeperApp keeper) {
		this.keeper = keeper;
		this.currentUser = keeper.getCurrentUser();

		this.selectedIndex = -1;

		initActions();

		loadData();
		initUI();
		
		cpAmount.addFocusListener(new FocusListener() {
			
			public void focusLost(FocusEvent e) {
				//reload data
				if("".equals(cpAmount.getText()) || cpAmount.getText() == null){
					
				}
				else {
					int amount = "".equals(cpAmount.getText()) ? 0 : Integer.valueOf(cpAmount.getText());
					int price = "".equals(cpPrice.getText()) ? 0: Integer.valueOf(cpPrice.getText());
					cpTotal.setText(String.valueOf((int)amount * price));
					
//					updateTotals(amount * price);
				}
				
			}

			public void focusGained(FocusEvent e) {
				
			}

		});
		
		cpPrice.addFocusListener(new FocusListener() {
			
			public void focusLost(FocusEvent e) {
				//reload data
				if("".equals(cpPrice.getText()) || cpPrice.getText() == null){
					
				}
				else {
					int amount = "".equals(cpAmount.getText()) ? 0 : Integer.valueOf(cpAmount.getText());
					int price = "".equals(cpPrice.getText()) ? 0: Integer.valueOf(cpPrice.getText());
					cpTotal.setText(String.valueOf((int)amount * price));
					
//					updateTotals(amount * price);
				}
				
			}

			public void focusGained(FocusEvent e) {
				
			}
		});
	}

	protected void updateTotals() {
		float totals = 0;
		for (OrderItem item : data) {
			totals = totals + item.getTotal();
		}
		
		cpTotals.setText(String.valueOf((int)(totals)));
	}

	private void loadData() {
		data = 	orderItemDAO.findAll();	
		for (OrderItem item : data) {
			ProductOrder order = orderDAO.findByPK(item.getOrderId());
			item.setOrder(order);
		}
		
		keeper.refreshStatus();
	}

	private void initActions() {
		insertAction = new AbstractAction("新增销售") {
			private static final long serialVersionUID = 5056698643009336063L;

			public void actionPerformed(ActionEvent e) {
				insert();
			}
		};

		deleteAction = new AbstractAction("\u5220\u9664") {
			private static final long serialVersionUID = -4608405524916997614L;

			public void actionPerformed(ActionEvent e) {
				delete();
			}
		};

		addAction = new AbstractAction("添加产品") {
			private static final long serialVersionUID = 6989199497316998154L;

			public void actionPerformed(ActionEvent e) {
				add();
			}
		};

		cancelAction = new AbstractAction("\u53D6\u6D88") {
			private static final long serialVersionUID = 6989199497316998154L;

			public void actionPerformed(ActionEvent e) {
				cancel();
			}
		};

		completeAction = new AbstractAction("完成") {
			private static final long serialVersionUID = 6989199497316998154L;

			public void actionPerformed(ActionEvent e) {
				complete();
			}

		};
		
		deleteAction.setEnabled(false);
	}

	private void initUI() {
		btnDelete = new JCButton(deleteAction);
		btnInsert = new JCButton(insertAction);
		btnAdd = new JCButton(addAction);
		btnCancel = new JCButton(cancelAction);
		btnComplete = new JCButton(completeAction);
		
		btnDelete.setPreferredSize(new Dimension(-1, 21));
		btnInsert.setPreferredSize(btnDelete.getPreferredSize());
		btnAdd.setPreferredSize(btnDelete.getPreferredSize());
		btnCancel.setPreferredSize(btnDelete.getPreferredSize());
		btnComplete.setPreferredSize(btnDelete.getPreferredSize());
		
		btnAdd.setVisible(false);
		btnCancel.setVisible(false);
		btnComplete.setVisible(false);
		
		EmptyComponent centerParent = new EmptyComponent();
		setLayout(new BorderLayout());
		centerParent.setLayout(new BorderLayout(0, 3));
		createCenter();
		createBottom();

		this.add(centerParent, BorderLayout.CENTER);

		if (center != null) {
			centerParent.add(center, BorderLayout.CENTER);
		}

		if (top != null) {
			centerParent.add(top, BorderLayout.NORTH);
		}

		if (bottom != null) {
			centerParent.add(bottom, BorderLayout.SOUTH);
		}

		loadUsers();
		loadStatus();
		loadCustomer();
		loadOperationType();
		loadProduct();
		
	}

	private void loadProduct() {
		List<Card> cards = cardDAO.findAll();
		
		cpProducts.removeAllItems();
		for (Card c : cards) {
			cpProducts.addItem(c.getName());
		}
		cpProducts.setSelectedIndex(-1);		
	}

	private void loadUsers() {
		List<User> users = UserUtils.getInstance().getAllUsers();
	
		cpUser.removeAllItems();
		for (User user : users) {
			cpUser.addItem(user.getName());
		}
		cpUser.setSelectedItem(currentUser.getName());
		
	}
	
	private void loadCustomer() {
		List<Customer> customers = customerDAO.findAll();
	
		cpCustomer.removeAllItems();
		for (Customer c : customers) {
			cpCustomer.addItem(c.getName());
		}
		cpCustomer.setSelectedIndex(-1);
	}
	
	private void loadOperationType() {
		cpPurpose.removeAllItems();
		cpPurpose.addItem("销售");
		cpPurpose.addItem("客户测试");
		cpPurpose.setSelectedIndex(0);
	}
	
	private void loadStatus() {
		cpStatus.removeAllItems();
		cpStatus.addItem("未付款");
		cpStatus.addItem("已付款");
		cpStatus.setSelectedIndex(0);
	}

	public void reload(){
		model.refreshUI();
	}

	protected JComponent createBottom() {

		bottom = new EmptyComponent();
		bottom.setBorder(new CompoundBorder(new EmptyBorder(0, 0, 0, 0), new LineBorder(new Color(84, 165, 213))));
		bottom.setPreferredSize(new Dimension(-1, 77));
		bottom.setLayout(new BorderLayout());
		bottom.add(createDetailComponent(), BorderLayout.CENTER);

		EmptyComponent buttonContainer = new EmptyComponent();
		buttonContainer.setLayout(new LineLayout(3, 0, 5, 0, 3, LineLayout.TRAILING, LineLayout.TRAILING,
				LineLayout.VERTICAL));
		buttonContainer.setPreferredSize(new Dimension(85, -1));
		buttonContainer.add(btnAdd, LineLayout.END_FILL);

		buttonContainer.add(btnDelete, LineLayout.END_FILL);
		buttonContainer.add(btnComplete, LineLayout.END_FILL);

		buttonContainer.add(btnInsert, LineLayout.END_FILL);
		buttonContainer.add(btnCancel, LineLayout.END_FILL);
		
		bottom.add(buttonContainer, BorderLayout.EAST);

		return bottom;
	}

	protected JComponent createCenter() {
		final Class<?>[] columnsClass = { Integer.class, String.class,String.class,String.class,Timestamp.class,String.class,
				Integer.class, String.class, Float.class, Float.class,
				String.class, String.class };
		final String[] getMethodsName = { "getOrderId", "getCustomer", "getUser", "getOperator", "getCreated", "getName", "getAmount",
				"getUnit", "getPrice", "getTotal", "getPurpose", "getStatus" };
		final String[] setMethodsName = { "setOrderId", "setCustomer", "setUser", "setOperator", "setCreated", "setName", "setAmount",
				"setUnit", "setPrice", "setTotal", "setPurpose", "setStatus" };
		final int[] columnsPreferredWidth = { 10, 40, 10, 10, 60, 40, 10, 10, 20, 20, 40, 40 };
		EmptyComponent ec = new EmptyComponent();
		JCScrollTable scTable = new JCScrollTable();
		table = scTable.getTable();
		model = new CommonTableModel<OrderItem>(table, COLUMNS_NAME, columnsClass, getMethodsName, setMethodsName, data);
		TableRowSorter<CommonTableModel<OrderItem>> sorter = new TableRowSorter<CommonTableModel<OrderItem>>(model);

		scTable.setAlpha(0.0f);
		scTable.setColumnControlEnabled(false);
		ec.setLayout(new BorderLayout());
		ec.add(scTable, BorderLayout.CENTER);
		table.setModel(model);
		table.setDragEnabled(false);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.setRowSorter(sorter);
		table.setRendererOpaque(false);
		((JCTableHeader) table.getTableHeader()).setShowPopupMenu(false);
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				whenSelectionChanged(e);
			}
		});
		table.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				select(e);
			}

			public void mouseReleased(MouseEvent e) {
				showPopupMenu(e);
			}
		});

		for (int i = 0; i < columnsPreferredWidth.length; i++) {
			table.getColumnModel().getColumn(i).setPreferredWidth(columnsPreferredWidth[i]);
		}

		return center = ec;
	}

	private JComponent createDetailComponent() {
		EmptyComponent ec = new EmptyComponent();
		EmptyComponent firstRow = new EmptyComponent();
		EmptyComponent secondRow = new EmptyComponent();

		JCLabel lbCustomer = new JCLabel("客户");
		JCLabel lbUser = new JCLabel("经手人");
		JCLabel lbTotals = new JCLabel("总货款");
		JCLabel lbMemo = new JCLabel("备注");
		JCLabel lbLogid= new JCLabel("出仓流水");

		Border border = new EmptyBorder(0, 0, 0, 5);
		cpUser =  new JCComboBox();
		cpCustomer =  new JCComboBox();
		cpTotals =  new JCNumberField(0, 0, 9999999);
		cpMemo = new JCScrollText();
		cpMemo.getEditor().setLineWrap(true);
		cpLogid = new JCTextField();
		
		firstRow.setLayout(new BoxLayout(firstRow, BoxLayout.X_AXIS));
		firstRow.setPreferredSize(new Dimension(-1, 25));

		firstRow.add(ecCustomer = createTitledComponent(lbCustomer, cpCustomer, border, 3));
		firstRow.add(ecUser = createTitledComponent(lbUser, cpUser, border, 3));
		firstRow.add(ecLogid = createTitledComponent(lbLogid, cpLogid, border, 3));
		firstRow.add(ecTotals = createTitledComponent(lbTotals, cpTotals, border, 3));
		firstRow.add(ecMemo = createTitledComponent(lbMemo, cpMemo, border, 3));

		ec.setLayout(new BorderLayout(0, 5));
		ec.setBorder(new EmptyBorder(3, 5, 2, 2));

		ecCustomer.setPreferredSize(new Dimension(100, -1));
		ecUser.setPreferredSize(new Dimension(30, -1));
		ecTotals.setPreferredSize(new Dimension(30, -1));
		ecLogid.setPreferredSize(new Dimension(50, -1));
		ecMemo.setPreferredSize(new Dimension(250, -1));
		
		JCLabel lbProduct = new JCLabel("产品");
		JCLabel lbPurpose = new JCLabel("操作类型");
		JCLabel lbStatus = new JCLabel("是否已付款");
		JCLabel lbPrice = new JCLabel("单价");
		JCLabel lbAmount = new JCLabel("数量");
		JCLabel lbTotal= new JCLabel("总额");
		
		secondRow.setLayout(new BoxLayout(secondRow, BoxLayout.X_AXIS));
		secondRow.setPreferredSize(new Dimension(-1, 25));

		cpProducts = new JCComboBox();
		cpPurpose = new JCComboBox();
		cpStatus = new JCComboBox();
		cpPrice = new JCNumberField(0, 1, 99999);
		cpAmount = new JCNumberField(0, 1, 9999);
		cpTotal= new JCNumberField(0, 1, 9999999);
		
		secondRow.add(ecProducts = createTitledComponent(lbProduct, cpProducts, border, 3));
		secondRow.add(ecPurpose = createTitledComponent(lbPurpose, cpPurpose, border, 3));
		secondRow.add(ecStatus = createTitledComponent(lbStatus, cpStatus, border, 3));
		secondRow.add(ecPrice = createTitledComponent(lbPrice, cpPrice, border, 3));
		secondRow.add(ecAmount = createTitledComponent(lbAmount, cpAmount, border, 3));
		secondRow.add(ecTotal = createTitledComponent(lbTotal, cpTotal, border, 3));

		ecProducts.setPreferredSize(new Dimension(100, -1));
		ecPurpose.setPreferredSize(new Dimension(100, -1));
		ecStatus.setPreferredSize(new Dimension(100, -1));
		ecPrice.setPreferredSize(new Dimension(100, -1));
		ecAmount.setPreferredSize(new Dimension(30, -1));
		ecTotal.setPreferredSize(new Dimension(100, -1));		
		
		ec.add(firstRow, BorderLayout.NORTH);
		ec.add(secondRow, BorderLayout.SOUTH);
		
		resetTextStatus(false);
		
		return ec;
	}

	private JComponent createTitledComponent(JComponent titleComponent, JComponent component, Border border, int hgap) {
		EmptyComponent ec = new EmptyComponent();
		ec.setBorder(border);
		ec.setLayout(new BorderLayout(hgap, 0));
		ec.add(component, BorderLayout.CENTER);

		if (titleComponent != null) {
			ec.add(titleComponent, BorderLayout.WEST);
		}

		return ec;
	}

	private void resetDetailValues() {
		if (bottom.isVisible()) {
			if (currentData == null) {
				clearValues();
			} else {
				fillValues();
			}

			resetTextStatus(false);
			resetButtonStatus(false);
			
		}
	}

	private void clearValues() {
		//cpUser.setSelectedIndex(-1);
		//cpStatus.setSelectedIndex(-1);
		cpMemo.getEditor().setText(null);
		cpProducts.setSelectedIndex(-1);
		//cpPurpose.setSelectedIndex(-1);
		cpPrice.setText(null);
		cpAmount.setText(null);
		cpTotal.setText(null);
		//cpStatus.setSelectedIndex(-1);
	}

	private void fillValues() {
		cpProducts.setSelectedItem(currentData.getName());
		cpPurpose.setSelectedItem(currentData.getPurpose());
		cpPrice.setText(String.valueOf((int)currentData.getPrice()));
		cpAmount.setText(String.valueOf((int)currentData.getAmount()));
		cpTotal.setText(String.valueOf((int)currentData.getTotal()));
		cpStatus.setSelectedItem(currentData.getStatus());
	}

	private void resetTextStatus(boolean editable) {
		cpCustomer.setEnabled(editable);
		cpStatus.setEnabled(editable);
		cpPurpose.setEnabled(editable);
		cpProducts.setEnabled(editable);
		cpTotal.setEditable(editable);
		cpTotals.setEditable(editable);
		cpAmount.setEditable(editable);
		cpLogid.setEditable(editable);
		cpPrice.setEditable(editable);
		cpUser.setEnabled(editable);
		cpMemo.setEditable(editable);
	}

	private void resetButtonStatus(boolean modifying) {
		btnAdd.setVisible(modifying);
		btnCancel.setVisible(modifying);
		btnInsert.setVisible(!modifying);
		btnDelete.setVisible(!modifying);
		btnComplete.setVisible(modifying);
	}

	private void select(MouseEvent e) {
		int row = table.rowAtPoint(e.getPoint());

		if (row >= 0 && SwingUtilities.isRightMouseButton(e)) {
			table.getSelectionModel().setSelectionInterval(row, row);
		} else if (row < 0 && !SwingUtilities.isMiddleMouseButton(e)) {
			if (selectedIndex >= 0) {
				table.clearSelection();
			} else {
				resetDetailValues();
			}
		}
	}

	private void showPopupMenu(MouseEvent e) {
		if (popup != null && SwingUtilities.isRightMouseButton(e)) {
			popup.show((Component) e.getSource(), e.getX(), e.getY());
		}
	}

	private void whenSelectionChanged(ListSelectionEvent e) {
		currentData = table.getSelectedRow() < 0 ? null : model.getSelectedRowData();
		boolean selectedEmpty = (selectedIndex = table.getSelectedRow()) < 0;
		deleteAction.setEnabled(!selectedEmpty);
		resetDetailValues();
	}

	protected void resetRowValues(OrderItem orderItem, ProductOrder order) {
		order.setCustomer(cpCustomer.getSelectedItem().toString());
		order.setUser(cpUser.getSelectedItem().toString());
		order.setOperator(currentUser.getName());
		order.setCreated(new Timestamp(System.currentTimeMillis()));
		
		orderItem.setOrder(order);
		orderItem.setName(cpProducts.getSelectedItem().toString());
		orderItem.setStatus(cpStatus.getSelectedItem().toString());
		orderItem.setPurpose(cpPurpose.getSelectedItem().toString());
		orderItem.setPrice(Float.valueOf(cpPrice.getText()));
		orderItem.setAmount(Integer.valueOf(cpAmount.getText()));
		orderItem.setTotal(orderItem.getPrice() * orderItem.getAmount());
	}

	public void cancel() {
		btnAdd.setActionCommand(null);
		refresh();
		resetDetailValues();
	}

	private void complete() {
		
		if(!data.isEmpty()){
			ProductOrder order = new ProductOrder();
			String customer = cpCustomer.getSelectedItem().toString();
			order.setCustomer(customer);
			order.setCreated(new Timestamp(System.currentTimeMillis()));
			order.setOperator(currentUser.getName());
			order.setUser(cpUser.getSelectedItem().toString());
			order.setMemo(cpMemo.getEditor().getText());
			order.setTotal(updateTotal());
			order.setNeeds(updateNeeds());
			order.setBack(updateBack());
			
			orderDAO.add(order);
			
			CustomerMoney cm = customerMoneyDAO.findByPK(customer);
			boolean existing = true;
			if(cm == null){
				cm = new CustomerMoney();
				existing = false;
			}
				
			cm.setCustomer(customer);
			cm.setAllmoney(existing ? (cm.getAllmoney() + order.getTotal()) : order.getTotal());
			cm.setReturnmoney(existing ? cm.getReturnmoney() + order.getBack() : order.getBack());
			cm.setModified(new Timestamp(System.currentTimeMillis()));
			cm.setMemo(existing ? cm.getMemo() + "|" + order.getId() : "" + order.getId());
			
			if(existing)
				customerMoneyDAO.update(cm);
			else 
				customerMoneyDAO.add(cm);
			
			for (OrderItem item : data) {
				item.setOrderId(order.getId());
				orderItemDAO.add(item);
			}

			List<ProductAmount> list = prepareProductAmounts();
			updateStore(list, order.getId());
			
			print(customerDAO.findByPK(customer), order, data, list, cpLogid.getText());
		}
		
		//show result and print
		refresh();
		
		resetButtonStatus(false);
		resetTextStatus(true);
//		btnDelete.setVisible(false);
	}
	
	private float updateNeeds() {
		float total = 0f;
		for (OrderItem item : data) {
			if("未付款".equals(item.getStatus())){
				total = total + item.getAmount() * item.getPrice();
			}
		}
		return total;
		
	}
	
	private float updateTotal() {
		float total = 0f;
		for (OrderItem item : data) {
			total = total + item.getAmount() * item.getPrice();
		}
		return total;

	}
	
	private float updateBack() {
		float total = 0f;
		for (OrderItem item : data) {
			if("已付款".equals(item.getStatus())){
				total = total + item.getAmount() * item.getPrice();
			}		}
		return total;

	}
	

	private void updateStore(List<ProductAmount> list, int id) {
		for (ProductAmount productAmount : list) {
			ProductStore ps = productStoreDAO.findByPK(productAmount.getName());
			if (ps != null) {
				ps.setAmount(ps.getAmount() - productAmount.getAmount());
				ps.setModified(new Timestamp(System.currentTimeMillis()));
				productStoreDAO.updateStore(ps);
				
				PStoreLog log = new PStoreLog();
				log.setCreated(new Timestamp(System.currentTimeMillis()));
				log.setAmount(0-productAmount.getAmount());
				log.setUser(cpUser.getSelectedItem().toString());
				log.setAction(StoreChangeActions.SALE.getMessage());
				log.setPid(productAmount.getName());
				log.setOutId(id);
				log.setOperator(currentUser.getName());
				log.setMemo("出仓流水:" + cpLogid.getText());
				pStoreLogDAO.add(log);
			}
		}

	}

	private List<ProductAmount> prepareProductAmounts() {
		List<Composite> cs =  compositeDAO.findAll();
		Random rand =new Random();
		
		List<ProductAmount> list = new ArrayList<ProductAmount>();
		for (OrderItem item : data) {
			ProductAmount pa = new ProductAmount();
			pa.setName(cs.get(rand.nextInt(cs.size() - 1)).getName());
			pa.setAmount((int)item.getAmount());
			list.add(pa);
		}
		return list;
	}

	private void print(Customer customer, ProductOrder order, List<OrderItem> data, List<ProductAmount> list, String logId) {
		SaleResultFrame print = new SaleResultFrame(customer, order, data, list, logId);
		print.setSize(595, 760);
		print.setVisible(true);
	}

	protected boolean checkInput() {
		return true;
	}

	protected boolean checkFilter(User data) {
		return true;
	}

	public void add() {
		if (!btnAdd.isVisible() || !checkInput()) {
			return;
		}

		OrderItem orderItem = new OrderItem();
		ProductOrder order = new ProductOrder();

		if (checkNull(orderItem)) {
			resetRowValues(orderItem, order);
			
			model.insertRowData(orderItem);
			int row = model.convertRowIndexesToView(model.getRowCount() - 1)[0];
			table.getSelectionModel().setSelectionInterval(row, row);

//			updateTotals();
			
			resetButtonStatus(true);
			resetTextStatus(false);
			cpTotals.setEditable(true);
			cpStatus.setEnabled(true);
			cpPurpose.setEnabled(true);
			cpProducts.setEnabled(true);
			cpTotal.setEditable(true);
			cpAmount.setEditable(true);
			cpPrice.setEditable(true);
		}

	}

	private boolean checkNull(OrderItem orderItem) {
		if (cpCustomer.getSelectedItem() == null || "".equals(cpAmount.getText()) || cpUser.getSelectedItem() == null
				|| "".equals(cpLogid.getText()) || "".equals(cpPrice.getText()) || "".equals(cpTotal.getText()) || cpProducts.getSelectedItem() == null ||cpPurpose.getSelectedItem() == null) {

			JCMessageBox.createErrorMessageBox(keeper.getMainFrame(), "必填项为空", "请输入所有必填项").open();

			return false;
		}

		if(checkStore(orderItem)){
			JCMessageBox.createErrorMessageBox(keeper.getMainFrame(), "库存不足", "电脑板库存不足,请核对!").open();
			return false;
		}
		
		return true;			
	}

	private boolean checkStore(OrderItem orderItem) {
		List<OrderItem> all = model.getAllRowDatasOnView();
		int amount = 0;
		if (all != null) {
			for (OrderItem oi : all) {
				amount += oi.getAmount();
			}
		}
		amount += orderItem.getAmount();

		if (productStoreDAO.findSumAmount() < amount) {
			return true;
		}
		return false;

	}

	public void insert() {
		clear();
		
		btnAdd.setActionCommand(CMD_ADDMORE);
		resetTextStatus(true);
		resetButtonStatus(true);

		clearValues();
		cpCustomer.requestFocus();
		
	}

	public void delete() {
		String message = "\u786E\u5B9A\u8981\u5220\u9664\u8BE5\u8BB0\u5F55\u5417\uFF1F";
		JCMessageBox box = JCMessageBox.createQuestionMessageBox(keeper.getMainFrame(), "\u5220\u9664", message);

		if (box.open() == JCMessageBox.YES_OPTION) {
			model.delRowOnViewAt(selectedIndex);
		}
	}

	@Override
	public String getType() {
		return "商品销售";
	};


	@Override
	public void refresh() {
		loadData();
		model.delAllRow();
		model.setDataList(data);
		model.getTable().repaint();
		model.refreshRowOnView(0);
		
		loadCustomer();
		loadOperationType();
		loadProduct();
		loadStatus();
		loadUsers();
		
		keeper.refreshStatus();
	}
	
	void clear(){
		data.clear();
		model.delAllRow();
		model.setDataList(data);
		model.getTable().repaint();
		model.refreshRowOnView(0);
		
		keeper.refreshStatus();
	}
}
